package com.sneakxy.cloudbase.platform.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sneakxy.cloudbase.platform.bean.Account;
import com.sneakxy.cloudbase.platform.bean.UploadFile;
import com.sneakxy.cloudbase.platform.service.UploadFileClient;
import com.sneakxy.cloudbase.platform.utils.web.Response;

@Controller
@RequestMapping("/api/editor/ueditor/")
public class UEditorFileController extends BaseController {

	@Autowired
	private UploadFileClient uploadFileClient;
	
	@SuppressWarnings("deprecation")
	@RequestMapping(value="image/{id}", method= {RequestMethod.GET, RequestMethod.POST})
	public void image(HttpServletResponse response, @PathVariable String id) throws IOException, MyException {
		Response<UploadFile> res = uploadFileClient.one(id);
		UploadFile file = res.getData();
		//私人文件
		if(StringUtils.equals(file.getExtent(), UploadFile.EXTENT_PRIVATE)) {
			Account account = (Account) this.getLoginAccount();
			if(!StringUtils.equals(account.getId(), file.getOwner())) {
				throw new UnauthorizedException("您没有权限下载此文件.");
			}
		}
		feign.Response fResponse = uploadFileClient.download(id);
		Iterator<Entry<String, Collection<String>>> it = fResponse.headers().entrySet().iterator();
		Entry<String, Collection<String>> header = null;
		while(it.hasNext()) {
			header = it.next();
			response.setHeader(header.getKey(), StringUtils.join(header.getValue(), ";"));
		}
		InputStream input = fResponse.body().asInputStream();
		OutputStream output = response.getOutputStream();
		IOUtils.copy(input, output);
		output.flush();
		IOUtils.closeQuietly(input);
		IOUtils.closeQuietly(output);
	}
	
	@RequestMapping(value="video/{id}", method= {RequestMethod.GET, RequestMethod.POST})
	public void video(HttpServletResponse response, @PathVariable String id) throws IOException, MyException {
		this.image(response, id);
	}
	
	@RequestMapping(value="file/{id}", method= {RequestMethod.GET, RequestMethod.POST})
	public void file(HttpServletResponse response, @PathVariable String id) throws IOException, MyException {
		this.image(response, id);
	}
	
}
